import { asyncRoutes, constantRoutes } from '@/router'
import { getUserPermissionByToken } from '@/api/sys_role'
import { param2Obj } from '@/utils/index'
import { MessageBox } from 'element-ui'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export function generaMenu(routes, data, hasParent, parent) {
  data.forEach(item => {
    const query = param2Obj(item.path)
    const menu = {
      query,
      originPath: item.path,
      path: hasParent ? item.path.replace('/', '').split('?')[0] : item.path,
      component: item.component === '#' ? Layout : resolve => require([`@/views/${item.component}`], resolve),
      children: [],
      name: item.name || '',
      redirect: item.redirect || '',
      hidden: item.hidden,
      meta: {
        title: item.meta.title,
        noCache: !item.meta.keepAlive,
        icon: item.meta.icon || '',
        activeMenu: item.hidden && parent ? (parent.path + parent.redirect).replace('//', '/') : ''
      }
    }
    if (item.children) {
      generaMenu(menu.children, item.children, true, item)
    }
    routes.push(menu)
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {

  generateRoutes({
    commit,
    dispatch
  }, roles) {
    return new Promise(resolve => {
      console.log(asyncRoutes)
      const loadMenuData = []
      getUserPermissionByToken().then(res => {
        const data = res.result.menu
        if (!data.length) {
          MessageBox.confirm('您没有任何权限，可请管理员设置后重新登录', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            dispatch('user/resetToken', {}, { root: true }).then(() => {
              location.href = location.origin + '/#/'
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消'
            // })
          })
        }
        Object.assign(loadMenuData, data)
        generaMenu(asyncRoutes, loadMenuData)
        // let accessedRoutes
        // if (roles.includes('admin')) {
        //   // alert(JSON.stringify(asyncRoutes))
        //   accessedRoutes = asyncRoutes || []
        // } else {
        //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        // }
        const accessedRoutes = asyncRoutes || []
        commit('SET_ROUTES', accessedRoutes)
        console.log(accessedRoutes)
        console.log(constantRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
